package com.christina.controller;

import com.christina.dto.LoginRequest;
import com.christina.dto.RegisterRequest;
import com.christina.service.UserService;
import com.christina.utils.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;

/**
 * 认证控制器
 * 
 * @author Christina
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/auth")
@Tag(name = "用户认证", description = "用户注册、登录等认证相关接口")
public class AuthController {

    private final UserService userService;

    public AuthController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    @Operation(summary = "用户注册", description = "新用户注册账号")
    public Result<String> register(@Valid @RequestBody RegisterRequest request) {
        log.info("用户注册请求: {}", request.getUsername());
        
        userService.register(request);
        log.info("用户{}注册成功", request.getUsername());
        
        return Result.success("注册成功，欢迎使用Christina智能助手！");
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "用户登录获取访问令牌")
    public Result<LoginResponse> login(@Valid @RequestBody LoginRequest request) {
        log.info("用户登录请求: {}", request.getUsername());
        
        String token = userService.login(request.getUsername(), request.getPassword());
        log.info("用户{}登录成功", request.getUsername());
        
        LoginResponse response = LoginResponse.builder()
            .token(token)
            .tokenType("Bearer")
            .expiresIn(86400) // 24小时
            .message("登录成功，欢迎回来！")
            .build();
        
        return Result.success("登录成功", response);
    }

    /**
     * 用户登出
     */
    @PostMapping("/logout")
    @Operation(summary = "用户登出", description = "用户登出，令牌失效")
    public Result<String> logout() {
        // 这里可以实现JWT黑名单逻辑
        log.info("用户登出");
        return Result.success("登出成功，期待您的再次使用！");
    }

    /**
     * 登录响应DTO
     */
    @lombok.Data
    @lombok.Builder
    public static class LoginResponse {
        private String token;
        private String tokenType;
        private Integer expiresIn;
        private String message;
    }
}